package com.sunda.spmsweb.wmscontroller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmswms.entity.InventoryCheckAction;
import com.sunda.spmswms.service.IInventoryCheckActionDtlService;
import com.sunda.spmswms.service.IInventoryCheckActionService;
import com.sunda.spmswms.service.IInventoryCheckService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 仓库盘盈盘亏 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-05-10
 */
@RestController
@RequestMapping("/invcheckac")
@Api(tags = "仓库盘点盘盈盘亏接口", description = "仓库盘点盘盈盘亏接口")
public class InventoryCheckActionController {

    @Autowired
    IInventoryCheckActionService iInventoryCheckActionService;

    @Autowired
    IInventoryCheckActionDtlService iInventoryCheckActionDtlService;

    @Autowired
    IInventoryCheckService iInventoryCheckService;

    @PostMapping("/getInvCheckAcList")
    @ApiOperation(value="获取库存盘点盘盈盘亏列表",notes="获取库存盘点盘盈盘亏列表" +
            "{\n" +
            "  \"werks\":[\"CN01\",\"CM31\"],\n" +
            "  \"whsLocationCode\":[\"1011\",\"1061\"],\n" +
            "  \"inventoryCheckType\":\"X\",  // X-备件货, M-贸易货\n" +
            "  \"inventoryCheckCategory\":\"1\", //盘点类别 1-日常盘点 2-月度盘点 3-动态盘点 4-其它盘点\n" +
            "  \"createDate\":[\"20210401\",\"20210501\"],\n" +
            "  \"inventoryCheckId\":\"CN01-20210511-INV\",\n" +
            "  \"spmsId\":\"CN01-1061-20210708-002\",\n" +
            "  \"spmsStatus\":\"1\", //任务状态：1-待盘点；2-盘点中；3-复盘中；4-处理中；5-关闭(完成)\n" +
            "}", httpMethod = "POST")
    public ResponseResult getInvCheckAcList(@RequestBody JSONObject InvCheckFilter){
        return iInventoryCheckActionService.getInvCheckAcList(InvCheckFilter);
    }

    @GetMapping("/getInvCheckAcWithDtl")
    @ApiOperation(value = "根据uuid获取盘点单据详情数据", notes = "根据uuid获取盘点单据详情数据")
    public ResponseResult getInvCheckAcWithDtl(@RequestParam(required = true) String uuid) {
        return iInventoryCheckActionService.getInvCheckAcWithDtl(uuid);
    }

    @PostMapping("/updateInvCheckAc")
    @ApiOperation(value="新建或更新盘盈盘亏单",notes = "新建或更新盘盈盘亏单" +
            "{\n" +
            "  \"invCheckAc\": {\n" +
            "    \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "    \"spmsId\": \"盘盈盘亏单号\",\n" +
            "    \"inventoryActionType\": \"盘盈盘亏类别 1-盘盈 2-盘亏\",\n" +
            "    \"werks\": \"工厂\",\n" +
            "    \"whsLocationCode\": \"仓库\",\n" +
            "    \"inventoryCheckId\": \"盘点单号\",\n" +
            "    \"inventoryCheckResult\": \"盘点结果 1-账实相符 2-盘盈 3-盘亏 4-盘盈盘亏\",\n" +
            "    \"inventoryCheckType\": \"是否杂货 X-备件货 M-贸易货\",\n" +
            "    \"inventoryCheckCategory\": \"盘点类别 1-日常盘点 2-月度盘点 3-动态盘点 4-其它盘点\",\n" +
            "    \"inventoryCheckMold\": \"盘点类型 1-明盘 2-暗盘\",\n" +
            "    \"createDate\": \"创建日期\",\n" +
            "    \"spmsStatus\": \"任务状态：1-草稿 2-审批中 3-审批通过(待上传SAP) 4-关闭(完成) 5-审批不通过\",\n" +
            "    \"requester\": \"创建人工号\",\n" +
            "    \"operator\": \"盘点人\",\n" +
            "    \"reviewer\": \"复核人\",\n" +
            "    \"approver\": \"审批人\",\n" +
            "    \"createTime\": \"创建时间\",\n" +
            "    \"updateUsername\": \"更新人\",\n" +
            "    \"updateTime\": \"更新时间\",\n" +
            "    \"justification\": \"申请原因\",\n" +
            "    \"remarks\":\"备注\",\n" +
            "    \"currentStatus\":\"1\",\n" +
            "    \"targetStatus\":\"2\"\n" +
            "  },\n" +
            "  \"invCheckAcDtls\": [\n" +
            "    {\n" +
            "      \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "      \"taskRowId\": \"盘盈盘亏任务行号\",\n" +
            "      \"materialNo\": \"物料编号\",\n" +
            "      \"boxNote\": \"箱码\",\n" +
            "      \"inventoryQuantity\": \"库存数量\",\n" +
            "      \"checkQuantity\": \"实盘数量\",\n" +
            "      \"discrepancy\": \"差异数量\",\n" +
            "      \"basicUnit\": \"基本单位\",\n" +
            "      \"storageUuid\": \"储位UUID\",\n" +
            "      \"remarks\": \"备注\",\n" +
            "    }\n" +
            "  ]\n" +
            "}", httpMethod = "POST")
    public ResponseResult updateInvCheckAc(@RequestBody JSONObject InvCheckDoc){
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        return iInventoryCheckActionService.updateInvCheckAc(InvCheckDoc, userId);
    }

    @PostMapping("/invAcSaveAndSap")
    @ApiOperation(value="保存盘盈盘亏单，并且发送到SAP",notes = "保存盘盈盘亏单，并且发送到SAP" +
            "{\n" +
            "  \"invCheckAc\": {\n" +
            "    \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "    \"spmsId\": \"盘盈盘亏单号\",\n" +
            "    \"inventoryActionType\": \"盘盈盘亏类别 1-盘盈 2-盘亏\",\n" +
            "    \"werks\": \"工厂\",\n" +
            "    \"whsLocationCode\": \"仓库\",\n" +
            "    \"inventoryCheckId\": \"盘点单号\",\n" +
            "    \"inventoryCheckResult\": \"盘点结果 1-账实相符 2-盘盈 3-盘亏 4-盘盈盘亏\",\n" +
            "    \"inventoryCheckType\": \"是否杂货 X-备件货 M-贸易货\",\n" +
            "    \"inventoryCheckCategory\": \"盘点类别 1-日常盘点 2-月度盘点 3-动态盘点 4-其它盘点\",\n" +
            "    \"inventoryCheckMold\": \"盘点类型 1-明盘 2-暗盘\",\n" +
            "    \"createDate\": \"创建日期\",\n" +
            "    \"spmsStatus\": \"任务状态：1-草稿 2-审批中 3-审批通过(待上传SAP) 4-关闭(完成) 5-审批不通过\",\n" +
            "    \"requester\": \"创建人工号\",\n" +
            "    \"operator\": \"盘点人\",\n" +
            "    \"reviewer\": \"复核人\",\n" +
            "    \"approver\": \"审批人\",\n" +
            "    \"createTime\": \"创建时间\",\n" +
            "    \"updateUsername\": \"更新人\",\n" +
            "    \"updateTime\": \"更新时间\",\n" +
            "    \"justification\": \"申请原因\",\n" +
            "    \"remarks\":\"备注\",\n" +
            "    \"currentStatus\":\"1\",\n" +
            "    \"targetStatus\":\"3\"\n" +
            "  },\n" +
            "  \"invCheckAcDtls\": [\n" +
            "    {\n" +
            "      \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "      \"taskRowId\": \"盘盈盘亏任务行号\",\n" +
            "      \"materialNo\": \"物料编号\",\n" +
            "      \"boxNote\": \"箱码\",\n" +
            "      \"inventoryQuantity\": \"库存数量\",\n" +
            "      \"checkQuantity\": \"实盘数量\",\n" +
            "      \"discrepancy\": \"差异数量\",\n" +
            "      \"basicUnit\": \"基本单位\",\n" +
            "      \"storageUuid\": \"储位UUID\",\n" +
            "      \"remarks\": \"备注\",\n" +
            "    }\n" +
            "  ]\n" +
            "}\n" +
            "单据执行过程：首先状态从1更新到3待上传SAP；再从3提交SAP，成功则状态改为4提交SAP成功；失败则状态改为6提交SAP失败；" +
            "状态首次由3提交SAP时计算库存，重新提交6不计算库存；", httpMethod = "POST")
    public ResponseResult invAcSaveAndSap(@RequestBody JSONObject InvCheckDoc){
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            JSONObject invCheckAc = InvCheckDoc.containsKey("invCheckAc") ? InvCheckDoc.getJSONObject("invCheckAc") : null;
            JSONArray invCheckAcDtls = InvCheckDoc.containsKey("invCheckAcDtls") ? InvCheckDoc.getJSONArray("invCheckAcDtls") : null;
            if (null == invCheckAc || null == invCheckAcDtls) {
                return ResponseResult.error("Error, invCheckAc or invCheckAcDtls missed from the parameters, please double check");
            }
            InventoryCheckAction inventoryCheckAction = invCheckAc.toJavaObject(InventoryCheckAction.class);
            if(StringUtils.isEmpty(inventoryCheckAction.getUuid()) || StringUtils.isEmpty(inventoryCheckAction.getPostingDate())){
                return ResponseResult.error("UUID or Posting Date is blank");
            }
            String remarks = invCheckAc.getString("remarks");
            String currentStatus = invCheckAc.getString("currentStatus");
            ResponseResult resp = iInventoryCheckActionService.getInventoryCheckActionToSap(inventoryCheckAction.getUuid(), inventoryCheckAction.getPostingDate(), userId, remarks, currentStatus);
            if (null != resp && resp.getCode() == 200){
                iInventoryCheckActionDtlService.updateInvCheckDtl(invCheckAc.getString("uuid"), invCheckAcDtls);
                /**检查并关闭盘点单*/
                ResponseResult invChkRes=iInventoryCheckService.checkAndCloseInvChk(inventoryCheckAction.getInventoryCheckId());

                if(invChkRes.getCode()==200){
                    return iInventoryCheckActionService.getInvCheckAcWithDtl(invCheckAc.getString("uuid")).add("inventoryCheck",invChkRes.getObject("inventoryCheck",Object.class));
                }
                return iInventoryCheckActionService.getInvCheckAcWithDtl(invCheckAc.getString("uuid"));
            }
            return resp;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("Failed when update or send data to SAP");
        }

    }

//    @PostMapping("/getInvCheckActionToSap")
//    @ApiOperation(value="盘点结果提交SAP",notes="盘点结果提交SAP\n" +
//            "盘盈盘亏单据uuid，贸易货示例 uuid = 2bd35b830798445991e4f6c3adc3bde4 \n" +
//            "备件货示例 uuid = b860d9902dd84760af7ab62bf7b7e7eb \n" +
//            "postingDate 过账日期用户必输 示例 2021-05-20\n" +
//            "1.检查单据是否可被提交SAP；\n" +
//            "2.获取提交SAP表头、行数据；\n" +
//            "3.更新盘盈盘亏对应的仓库库存、储位库存，对于 提交SAP失败 状态下的单据忽略更新；\n" +
//            "4.记录仓库库存更新日志；记录储位更新日志；\n" +
//            "5.提交SAP；成功——更新盘点单据表头 状态4、过账日期、物料凭证、凭证年度 等字段信息；失败——更新表头状态6；记录日志；\n" +
//            "6.记录提交结果日志，如果失败则将SAP返回错误信息一起记录到日志里；记录单据更新日志；\n" +
//            "\n", httpMethod = "POST")
//    public ResponseResult getInventoryCheckActionToSap(String uuid, String postingDate){
//        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
//        return iInventoryCheckActionService.getInventoryCheckActionToSap(uuid, postingDate, userId);
//    }

    @PostMapping("/getICALogs")
    @ApiOperation(value="获取盘盈盘亏操作日志",notes="获取盘盈盘亏关联日志\n" +
            "示例 uuid = 2bd35b830798445991e4f6c3adc3bde4 或 b860d9902dd84760af7ab62bf7b7e7eb ", httpMethod = "POST")
    public ResponseResult getICALogs(String uuid){
        return ResponseResult.success().add("inventoryCheckActionLogs", iInventoryCheckActionService.getICALogs(uuid));
    }

}
